use gloo_net::http::Request;
use log::info;
use wasm_bindgen_futures::spawn_local;
use yew::prelude::*;

use super::components::topic::{Topic, TopicRequest, TopicResponse};
use crate::routes::main::MainRoute;
use yew_router::hooks::use_navigator;

#[function_component]
pub fn App() -> Html {
    let navigator = use_navigator().unwrap();
    let data = use_state(|| vec![]);
    let data_set = data.clone();

    // req
    let params = use_state(|| TopicRequest {
        page: 1,
        tab: "good".to_string(),
        limit: 10,
        mdrender: false,
    });

    // let req_params = params.clone();
    use_effect_with(params.clone(), move |req_params| {
        let req = req_params.clone();

        spawn_local(async move {
            let page = req.page.to_string();
            let limit = req.limit.to_string();
            let tab = req.tab.to_string();
            let mdrender = req.mdrender.to_string();
            let query = vec![
                ("page", &page),
                ("limit", &limit),
                ("tab", &tab),
                ("mdrender", &mdrender),
            ];
            let data: TopicResponse = Request::get("https://cnodejs.org/api/v1/topics")
                .query(query)
                .send()
                .await
                .unwrap()
                .json()
                .await
                .unwrap();

            data_set.set(data.data);
        });
    });

    let update_params = params.clone();
    let handle_jump = {
        let req_set = update_params.clone();

        Callback::from(move |num: i32| {
            let mut new_page = update_params.page + num;
            if new_page < 0 {
                new_page = 0;
            }
            req_set.set(TopicRequest {
                page: new_page,
                ..(*update_params).clone()
            });
        })
    };
    let jump = handle_jump.clone();
    let jump_prev = { Callback::from(move |_| jump.emit(-1)) };
    let jump = handle_jump.clone();
    let jump_next = { Callback::from(move |_| jump.emit(1)) };

    // view detail
    // fn view_detail(info: Topic) -> impl Fn(MouseEvent) -> () {
    //     move |_| {
    //         let data = info.clone();
    //         info!("{}", data.id);
    //         navigator.push(&MainRoute::CNodeDetail { id: info.id });
    //     }
    // }
    // let handle_view_detail = move |info: Topic| view_detail(info);
    let show_params = params.clone();

    // 列表数据渲染
    let list_items = data.iter().map(move |item| {
        let info = item.clone();
        let navigator = navigator.clone();

        let view_detail = Callback::from(move |_| {
            let id = info.id.clone();
            navigator.push(&MainRoute::CNodeDetail { id: id });
        });
        html! {
            <li key={format!("{}", &item.id)} onclick={view_detail}>
                <p>{format!("{}", &item.title)}</p>
            </li>
        }
    });
    html! {
        <div class="cnode list-page">
            <ul class="list">
                {for list_items}
            </ul>

            <div class="pagation-box">
                {if show_params.page>1 { html !{<button class="prev pagation-btn" onclick={jump_prev}>{"上一页"}</button>}}else {html!{}}}
                <button class="next pagation-btn" onclick={jump_next}>{"下一页"}</button>
            </div>
        </div>
    }
}
